import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'
import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader'
import {RoomEnvironment} from 'three/examples/jsm/environments/RoomEnvironment'

let renderer, camera, scene
let axesHelper
let controls
let mixer
let clock = new THREE.Clock()





initRenderer()
initCamera()
initScene()
initAxesHelper()
initControls()

initEnv()
loadModel()




window.addEventListener('resize', function () {
    camera.aspect = window.innerWidth / window.innerHeight
    camera.updateProjectionMatrix()
    renderer.setSize(window.innerWidth, window.innerHeight)
})


function initRenderer() {
    renderer = new THREE.WebGLRenderer()
    renderer.setPixelRatio(window.devicePixelRatio)
    renderer.setSize(window.innerWidth, window.innerHeight)
    document.body.appendChild(renderer.domElement)
}

function initCamera() {
    camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000)
    camera.position.set(4,4,4)
}

function initScene(params) {
    scene = new THREE.Scene()
    scene.background = new THREE.Color(0x888888)
}

function initAxesHelper(params) {
    axesHelper = new THREE.AxesHelper(3)
    scene.add(axesHelper)
}

function  initControls(params) {
    controls = new OrbitControls(camera, renderer.domElement)
}

function initEnv(params) {
    var pmeremGenerator = new THREE.PMREMGenerator(renderer)
    scene.environment = pmeremGenerator.fromScene(new RoomEnvironment(),0.001).texture
}

function loadModel(params) {
    const loader = new GLTFLoader()
    const dracoLoader = new DRACOLoader()
    dracoLoader.setDecoderPath('./draco/gltf/')
    loader.setDRACOLoader(dracoLoader)
    loader.load(
        'models/gltf/LittlestTokyo.glb',function (gltf) {
            console.log(gltf);
            const model = gltf.scene
            scene.add(model)
            gltf.scene.traverse(function (child) {
                if (child.isMesh) {
                    console.log(child);
                }
            });
            console.log(model.position);
            model.position.set(1, 1, 0)
            model.scale.set(0.01, 0.01, 0.01)
            
            //做动画
            mixer = new THREE.AnimationMixer(model)
            mixer.clipAction(gltf.animations[0]).play()
             animate()

        }
    )
}

function animate(params) {
    requestAnimationFrame(animate)
    const delta = clock.getDelta()
    mixer.update(delta)
    controls.update()
    renderer.render(scene,camera)
}

